package com.ganee.agora.view

import android.os.Bundle
import android.os.Vibrator
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.ganee.agora.R
import com.ganee.agora.viewmodel.ScanQrCodeViewModel
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.utils.ToastUtil
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.yanzhenjie.album.Action
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.AlbumFile
import com.yanzhenjie.album.api.widget.Widget
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.activity_scan_qr_code.*
import kotlinx.android.synthetic.main.toolbar_profile.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.json.JSONException
import org.json.JSONObject

/**
 * 扫描二维码页面
 */
@Route(path = Constance.ACTIVITY_URL_SCAN_QRCODE)
class ScanQrCodeActivity : BaseActivity<ScanQrCodeViewModel>() , QRCodeView.Delegate,View.OnClickListener{

    private val REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan_qr_code)
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        mZXingView.setDelegate(this)
        AndPermission.with(this@ScanQrCodeActivity)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted({ permissions ->
                })
                .onDenied({ permissions ->
                })
                .start()
        toolbarCancel.setOnClickListener(this)
        toolbarRight.setOnClickListener(this)
        toolbarTitle.text = "Check ticket"
        toolbarRight.text = "Album"
    }

    override fun getViewModel(): ScanQrCodeViewModel {
        return ViewModelProviders.of(this@ScanQrCodeActivity).get(ScanQrCodeViewModel::class.java)
    }

    override fun onStart() {
        super.onStart()
        mZXingView.startCamera() // 打开后置摄像头开始预览，但是并未开始识别
        //        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZXingView.startSpotAndShowRect() // 显示扫描框，并开始识别
    }

    override fun onStop() {
        mZXingView.stopCamera() // 关闭摄像头预览，并且隐藏扫描框
        super.onStop()
    }

    override fun onDestroy() {
        mZXingView.onDestroy() // 销毁二维码扫描控件
        super.onDestroy()
    }

    private fun vibrate() {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    override fun onScanQRCodeSuccess(result: String) {
        Log.i("eee", "result:$result")
        vibrate()
        if (!TextUtils.isEmpty(result)) {
            initHttpRequest(result)
        }
    }

    private fun initHttpRequest(ticketKey: String) {
        val requestData = JSONObject()
        try {
            requestData.put("ticketKey", ticketKey)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
        viewModel.verifyTicketInfo(requestBody)
        viewModel.data.observe(this, Observer<Any> {
            ToastUtil.showToast("Check Successfully")
            finish()
        })
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) { // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
//        var tipText: String = mZXingView.getScanBoxView().getTipText()
//        val ambientBrightnessTip = ""//"\n环境过暗，请打开闪光灯"
//        if (isDark) {
//            if (!tipText.contains(ambientBrightnessTip)) {
//                mZXingView.getScanBoxView().tipText = tipText + ambientBrightnessTip
//            }
//        } else {
//            if (tipText.contains(ambientBrightnessTip)) {
//                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
//                mZXingView.scanBoxView.tipText = tipText
//            }
//        }
    }

    override fun onScanQRCodeOpenCameraError() {
        Log.e("eee", "打开相机出错")
    }

    override fun onClick(v: View?) {
        when(v!!.id){
            R.id.toolbarCancel -> {
                finish()
            }
            R.id.toolbarRight -> {
                if (AndPermission.hasPermissions(this, Permission.CAMERA)) {
                    Album.album(this@ScanQrCodeActivity)
                            .singleChoice()
                            .widget(Widget.newLightBuilder(this).statusBarColor(ContextCompat.getColor(this, R.color.color_toolbar)).toolBarColor(ContextCompat.getColor(this, R.color.color_toolbar)).build())
                            .onResult(Action<ArrayList<AlbumFile>>() {
                                val picturePath = it[0].path
                                // 本来就用到 QRCodeView 时可直接调 QRCodeView 的方法，走通用的回调
                                mZXingView.decodeQRCode(picturePath)
                            })
                            .onCancel(Action<String>() {

                            })
                            .start()

                }
            }
        }
    }

}
